﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Mvc;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Service;

namespace LevenBlog.Core.Mvc
{
    public sealed class FileResult : ActionResult
    {
        public int FileID { get; set; }
        public IDbProvider Provider { get; set; }

        public FileResult(IDbProvider provider)
        {
            FileID = 0;
            Provider = provider;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            lb_file file = LevenBlog.Core.Service.File.Get(Provider, FileID);
            lb_config config = Config.Get(Provider);
            int length = 0;
            string filename = string.Empty;
            byte[] bs = null;
            string extname = string.Empty;
            if (file == null)
            {
                filename = config.logo.Replace('\\', '/');
                if (filename.IndexOf('/') > 0)
                    filename = filename.Substring(filename.LastIndexOf('/') + 1);
                extname = filename.Substring(filename.LastIndexOf('.') + 1);
                string filepath = context.HttpContext.Server.MapPath(string.Format("~/skins/{0}/{1}", config.skinpath, config.logo));
                FileInfo fi = new FileInfo(filepath);
                if (!fi.Exists)
                    throw new Exception("站点logo设置错误,不存在该文件.");
                bs = ReadFile(filepath, out length);
            }
            else
            {
                file.hits++;
                LevenBlog.Core.Service.File.Update(Provider, file);
                filename = string.Format("{0}.{1}", file.name, file.type);
                extname = file.type;
                string filepath = string.Format("{0}/{1}/{2}", Config.Get(Provider).uploadpath, file.path, file.name);
                filepath = context.HttpContext.Server.MapPath(filepath);
                bs = ReadFile(filepath, out length);
            }
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = GetContentType(extname);
            context.HttpContext.Response.AddHeader("Content-Disposition", "attachment;FileName=\"" + HttpUtility.UrlEncode(filename) + "\"");
            context.HttpContext.Response.AddHeader("Content-Length", length.ToString());
            context.HttpContext.Response.BinaryWrite(bs);
        }

        private byte[] ReadFile(string path, out int length)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] bs = new byte[(int)fs.Length];
            fs.Read(bs, 0, (int)fs.Length);
            length = (int)fs.Length;
            fs.Close();
            return bs;
        }

        private string GetContentType(string extName)
        {
            string type = string.Empty;
            extName=extName.Trim().ToLower();
            switch (extName)
            {
                case "jpg":
                case "jpeg":
                    type = "image/jpeg";
                    break;
                case "gif":
                    type = "image/gif";
                    break;
                case "png":
                    type = "image/png";
                    break;
                case "bmp":
                    type = "image/bmp";
                    break;
                default:
                    type = "application/octet-stream";
                    break;
            }
            return type;
        }
    }
}
